# -*- coding: utf-8 -*-
"""
@author 1: liuyw

本程序根据第一作者 liuyw的版本升级。
1.优化了订票流程结构
2.提供按席别抢票功能。
3.提供儿童票预订
4.优化抢票成功概率。

5.因为本程序抢票过程不能交互，也不适用于非IT人员，正开发.net的窗体版本，基本上快完工了

@Author 2 ,updated: James Yu 2018-01-06 james.yu@qq.com

"""
from splinter.browser import Browser
from time import sleep
import traceback
import time, sys
import datetime

class huoche(object):
    """docstring for huoche"""
    driver_name=''
    executable_path=''
    #用户名，密码
    username = u"your 12306 username"
    passwd = u"your password"
    # cookies值得自己去找, 下面两个分别是深圳, 重庆
    starts = u"%u6DF1%u5733%2CSZQ"
    ends = u"%u91CD%u5E86%2CCQW"
    # 时间格式2018-01-19
    dtime = u"2018-01-08"
	# 以下编程日期为：根据当前放票推算当天订票日期
    # dtime = (datetime.datetime.now() + datetime.timedelta(days = 29)).strftime('%Y-%m-%d')
    # 车次，选择第几趟，0则从上之下依次点击
    order = 0
    ###乘客名
    users = [u"乘客1",u"乘客2"]
    ##席位
    # xb = "ZE" #二等座
    # xb = "RW" #软卧
    xb = "YW" #硬卧
    pz=u"成人票"
	#儿童票数， 不能超过成人数量
	childrens = 0

    """网址"""
    ticket_url = "https://kyfw.12306.cn/otn/leftTicket/init"
    login_url = "https://kyfw.12306.cn/otn/login/init"
    initmy_url = "https://kyfw.12306.cn/otn/index/initMy12306"
    buy="https://kyfw.12306.cn/otn/confirmPassenger/initDc"
    login_url='https://kyfw.12306.cn/otn/login/init'
    
    def __init__(self):
        self.driver_name='chrome'
        self.executable_path='C:\Python27\selenium\webdriver\chromedriver.exe'

    def login(self):
        self.driver.visit(self.login_url)
        self.driver.fill("loginUserDTO.user_name", self.username)
        # sleep(1)
        self.driver.fill("userDTO.password", self.passwd)
        print u"等待验证码，自行输入..."
        while True:
            if self.driver.url != self.initmy_url:
                sleep(1)
            else:
                break

    def start(self):
        self.driver=Browser(driver_name=self.driver_name,executable_path=self.executable_path)
        self.driver.driver.set_window_size(1400, 1000)
        self.login()
        # sleep(1)
        self.driver.visit(self.ticket_url)

        print u"购票页面开始..."
        # sleep(1)
        # 加载查询信息
        self.driver.cookies.add({"_jc_save_fromStation": self.starts})
        self.driver.cookies.add({"_jc_save_toStation": self.ends})
        self.driver.cookies.add({"_jc_save_fromDate": self.dtime})

        self.driver.reload()

        # 搜索车次
        self.search()


    def search(self):
        try:
            script = """var yesP = document.querySelector('#queryLeftTable').querySelectorAll('[id^="%s"][class=yes]');
                    if (!yesP)
                    {
                        yesP = document.querySelector('#queryLeftTable').querySelectorAll('[id^="%s"][class]');
                    }
                    if (yesP)
                    {
                        yesP[0].parentElement.cells[12].querySelector('a').click();
                        /* for(var p in yesP)
                         {
                             p.parentElement.cells[12].querySelector('a').click();
                         }*/
                    }
                    
                    """ % (self.xb,self.xb)
            print script

            count=0
            if self.order!=0:
                while self.driver.url==self.ticket_url:
                    self.driver.find_by_text(u"查询").click()
                    count += 1
                    print u"循环点击查询... 第 %s 次" % count
                    # sleep(1)
                    try:
                        self.driver.find_by_text(u"预订")[self.order - 1].click()
                    except Exception as e:
                        print e
                        print u"还没开始预订"
                        continue
            else:
                while self.driver.url == self.ticket_url:
                    self.driver.find_by_text(u"查询").click()

                    count += 1
                    print u"循环点击查询... 第 %s 次" % count
                    # sleep(0.8)
                    try:
                        # for i in self.driver.find_by_text(u"预订"):
                        #     i.click()
                        #     sleep(1)

                        # james add
                        print u"执行脚本"
                        self.driver.execute_script(script)                        
                    except Exception as e:
                        print e
                        print u"还没开始预订 %s" %count
                        continue
            # 填写乘客
            self.fillPassenger()

        except Exception as e:
            print e

    def fillPassenger(self):
        try:
            print u"开始预订...选择用户..."

            # sleep(3)
            # self.driver.reload()
            # sleep(1)
            # 由sleep 改为 waitFor
            try:
                # 常用联系人列表
                if self.driver.is_element_present_by_id(id='normal_passenger_id',wait_time=3):
                    print self.driver.find_by_id('normal_passenger_id').__repr__()
                    print u'开始选择用户...'
                    for user in self.users:
                        self.driver.find_by_text(user).last.click()
					if childrens:
						for c in range(0,childrens):
							self.driver.find_by_id('addchild_%s' %(c+1)).click()
                else: # 重新查询
                    print "没有发现用户选择，暂停1秒 后 再查询"
                    sleep(1)
                    if self.driver.is_element_present_by_id(id='qd_closeDefaultWarningWindowDialog_id',wait_time=3): # 车票信息已过期 提示
                        self.driver.find_by_id(u"qd_closeDefaultWarningWindowDialog_id").click() # 确定
                    
                    self.search()

            finally:
                pass

            # 购买儿童票确认
            try:
                self.driver.find_by_text(u"确认").last.click()
            finally:
                pass

            self.submitOrder() # 提交订单
        except Exception as e:
            print e

    def submitOrder(self):
        try:
            print u"提交订单..."
            # sleep(1)

            try:
                if self.driver.is_element_present_by_id(id='submitOrder_id',wait_time=3):
                    print self.driver.find_by_id('submitOrder_id').__repr__()
                    # James Comment
                    self.driver.find_by_id('submitOrder_id').click()
            finally:
                pass

            # self.driver.find_by_text(self.pz).click()
            # self.driver.find_by_id('').select(self.pz)
            # # sleep(1)
            # self.driver.find_by_text(self.xb).click()
            # sleep(1)



            
            # print u"开始选座..."
            # self.driver.find_by_id('1D').last.click()
            # self.driver.find_by_id('1F').last.click()

            # sleep(1.5)
            print u"核对信息,准备提交订单..."
            try:
                if self.driver.is_element_present_by_id(id='qr_submit_id',wait_time=3):
                    print self.driver.find_by_id('qr_submit_id').__repr__()
                    # James Comment
                    self.driver.find_by_id('qr_submit_id').click()
                else:
                    self.driver.reload()
                    self.search()
            finally:
                pass
        except Exception as e:
            print e

if __name__ == '__main__':
    huoche=huoche()
    huoche.start()